﻿//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Microsoft Public License.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.ServiceModel.Web;
using System.Threading;

namespace BookStoreService.Tests.Tools
{
    public class TestService : IDisposable
    {
        private WebServiceHost host;
        private readonly Uri serviceUri;
        private static int s_lastHostId = 1;
        private const int NumberOfAttempts = 10;
        
        public TestService(Type serviceType)
        {
            int attempts = 0;
            for (;;)
            {
                int hostId = Interlocked.Increment(ref s_lastHostId);
                string hostName = "BookStoreDataService" + hostId;
                
                serviceUri = new Uri(
                    "http://localhost/Temporary_Listen_Addresses/" + hostName);
                
                host = new WebServiceHost(serviceType, serviceUri);
                try
                {
                    host.Open();
                    break;
                }
                catch (Exception e)
                {
                    host.Abort();
                    host = null;

                    if (attempts++ >= NumberOfAttempts)
                    {
                        string message = string.Format(
                            "Could not open a service after {0} attempts", 
                            NumberOfAttempts);
                        
                        throw new InvalidOperationException(message, e);
                    }
                }
            }
        }

        public void Dispose()
        {
            if (host != null)
            {
                host.Close();
                host = null;
            }
        }

        public Uri ServiceUri
        {
            get { return serviceUri; }
        }
    }
}
